
#include "dynamicarray.h"

void DynamicArray_Init(DynamicArray* dyn, TYPE type)
{
	dyn->type = type;
	dyn->array = (Type32*) malloc(sizeof(Type32));
	dyn->lenght = 0;
	dyn->reserved = 1;
}

void DynamicArray_Add(DynamicArray* dyn, Type32 element)
{
	if(dyn->lenght >= dyn->reserved)
	{
		realloc(dyn->array, sizeof(Type32) * dyn->reserved * 2);
		dyn->reserved *= 2;
	}
	dyn->array[dyn->lenght] = element;
	dyn->lenght++;
}

BOOL DynamicArray_Search(const DynamicArray* dyn, Type32 element)
{
	int i;
	for(i = 0; i <= dyn->lenght; i++)
	{
		if (Type32_Compare(dyn->type,dyn->array[i],element))
			return i;
	}
	return -1;
}

void DynamicArray_Remove(DynamicArray* dyn, Type32 element)
{
	int i = DynamicArray_Search(dyn,element);
	if (i != -1)
		DynamicArray_RemoveAt(dyn,i);
}

void DynamicArray_RemoveAt(DynamicArray* dyn, int index)
{
	int i;
	assert((index <= dyn->lenght) && (index >= 0));
	for(i = index; i < dyn->lenght; i++)
		dyn->array[i] = dyn->array[i+1];
	if(((float)dyn->lenght / 3) < dyn->reserved)
	{
		realloc(dyn->array, sizeof(void*) * dyn->lenght / 3);
		dyn->reserved /= 3;
	}
	dyn->lenght--;
}

void DynamicArray_Destroy(DynamicArray* dyn)
{
	free(dyn->array);
	dyn->array = NULL;
	dyn->reserved = 0;
	dyn->lenght = 0;
}
